package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.Thread.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional

public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private WmAutoScanService wmAutoScanService;
    @Autowired
    private WmNewsMapper wmNewsMapper;

    /**
     * 查询文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        Page page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> wrapper = Wrappers.lambdaQuery(WmNews.class).ge(dto.getBeginPubDate() != null, WmNews::getPublishTime, dto.getBeginPubDate())
                .le(dto.getEndPubDate() != null, WmNews::getPublishTime, dto.getEndPubDate())
                .like(StringUtils.isNotBlank(dto.getKeyword()), WmNews::getTitle, dto.getKeyword())
                .eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId())
                .eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus())
                .eq(WmNews::getUserId, WmThreadLocalUtils.getUser().getId())
                .orderByDesc(WmNews::getPublishTime);
        page(page, wrapper);
        // 封装结果返回
        PageResponseResult pageResponseResult = new PageResponseResult((int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal());
        pageResponseResult.ok(AppHttpCodeEnum.SUCCESS.getCode(), page.getRecords(), AppHttpCodeEnum.SUCCESS.getErrorMessage());
        return pageResponseResult;
    }


    /**
     * 发布文章或保存草稿
     *
     * @param dto
     * @return
     */
    @Autowired
    private WmTaskService wmTaskService;
    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
        //1，参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //数据处理
        WmNews wmNews = new WmNews();
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        BeanUtils.copyProperties(dto, wmNews);
        if (dto.getType() == -1) {
            wmNews.setType(null);
        }
        /*if(dto.getImages()!=null&&dto.getImages().size()>0){*/
        String image = String.join(",", dto.getImages());
        wmNews.setImages(image);
        saveOrUpdateWmNews(wmNews);
        //}
        if (dto.getStatus().equals(0)) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        // 处理内容中的图片，并返回图片链接列表
        List<String> imageUrls = handleImgByContent(dto.getContent());

        // 保存内容图片与内容的关系
        saveRelationWithContentImg(wmNews, imageUrls);

        // 保存封面图片与内容的关系
        saveRelationWithCoverImg(wmNews, dto, imageUrls);

        // 自动扫描wmNews的id
        //wmAutoScanService.autoScan(wmNews.getId());
        //5. 异步添加审核文章的任务  -- 发消息
        wmTaskService.addTask(wmNews);
        // 返回成功结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

    @Transactional
    @Override
    public ResponseResult DeleteById(Integer id) {
        if (id == null) {
            return ResponseResult.errorResult(501, "文章Id不可缺少");
        }
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(401, "文章不存在");
        }
        if (wmNews.getStatus() == 9) {
            return ResponseResult.errorResult(501, "文章已发布，不能删除");
        }
        wmNewsMapper.deleteById(id);
        wmNewsMaterialMapper.deleteById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
    @Autowired
    private KafkaTemplate kafkaTemplate;
    @Override
    public ResponseResult UpAndDown(WmNewDto wmNewDto) {
        WmNews wmNews = wmNewsMapper.selectById(wmNewDto.getId());
        if(wmNews==null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (wmNews.getStatus() != 9) {
            return ResponseResult.errorResult(501, "当前文章不是发布状态,不能上下架");
        }
        wmNews.setEnable(wmNewDto.getEnable());
        wmNewsMapper.updateById(wmNews);
        //发送消息到kafka携带：articleID和enable的值
        HashMap<String, Object> map = new HashMap<>();
        map.put("articleId",wmNews.getArticleId());
        map. put ("enable", wmNews. getEnable());
        kafkaTemplate.send("down_or_up_article", JSON.toJSONString(map));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

    @Override
    public ResponseResult selectByText(Integer id) {
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(401, "文章不存在");
        }
        return ResponseResult.okResult(wmNews);
    }

    private void saveRelationWithCoverImg(WmNews wmNews, WmNewsDto dto, List<String> imageUrls) {
        List<String> images = dto.getImages();
        if (dto.getType() == -1) {
            if (imageUrls != null && imageUrls.size() >= 1 && imageUrls.size() < 3) {
                wmNews.setType((short) 1);
                images = imageUrls.stream().limit(1).collect(Collectors.toList());
            } else if (imageUrls != null && imageUrls.size() >= 3) {
                wmNews.setType((short) 3);
                images = imageUrls.stream().limit(3).collect(Collectors.toList());
            } else {
                wmNews.setType((short) 0);
            }
            if (images != null && images.size() > 0) {
                wmNews.setImages(String.join(",", images));
            }
            updateById(wmNews);
        }
        if (images != null && images.size() > 0) {
            saveRelationWithImg(wmNews, images, (short) 1);
        }
    }

    private void saveRelationWithContentImg(WmNews wmNews, List<String> imageUrls) {
        saveRelationWithImg(wmNews, imageUrls, (short) 0);
    }

    private void saveRelationWithImg(WmNews wmNews, List<String> imageUrls, short type) {
        if (imageUrls != null && imageUrls.size() > 0) {
            //根据图片的url查找图片的id
            //对图片的url去重
            imageUrls = imageUrls.stream().distinct().collect(Collectors.toList());
            List<WmMaterial> dbMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery()
                    .in(WmMaterial::getUrl, imageUrls));

            List<Integer> idList = dbMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
            //批量保存
            Integer newsId = wmNews.getId();
            wmNewsMaterialMapper.saveRelations(idList, newsId, type);

        }
    }

    private List<String> handleImgByContent(String content) {
        ArrayList<String> res = new ArrayList<>();
        JSONArray objects = JSONArray.parseArray(content);
        for (Object object : objects) {
            JSONObject jsonObject = JSONObject.parseObject(object.toString());
            if ("image".equals(jsonObject.getString("type"))) {
                String imageUrl = jsonObject.getString("value");
                res.add(imageUrl);
            }
        }
        return res;
    }

    private void saveOrUpdateWmNews(WmNews wmNews) {
        wmNews.setSubmitedTime(new Date());
        if (wmNews.getId() != null) {
            //修改
            wmNewsMaterialMapper.delete(Wrappers.lambdaQuery(WmNewsMaterial.class)
                    .eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            //2.修改文章信息
            updateById(wmNews);
        } else {
            wmNews.setCreatedTime(new Date());
            save(wmNews);
        }
    }
}